package cn.com.pansky.action.bank;

import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.vsame.url2sql.sql.Model;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

import cn.com.pansky.getui.AppPush;
import cn.com.pansky.service.NoticeService;
import cn.com.pansky.service.OrderBackWriteService;

import com.alibaba.fastjson.JSONObject;
import com.gexin.rp.sdk.base.payload.APNPayload;
import com.gexin.rp.sdk.template.TransmissionTemplate;
import com.psbc.payment.client.SignatureService;

/**
 * 邮储支付交易接口
 * @author Administrator
 *
 */
public class PsbcPayResult extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PsbcPayResult() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		NoticeService notice = new NoticeService();
		OrderBackWriteService orderBackWriteService = new OrderBackWriteService(); // 银行支付成功，系统数据回填接口
//		Map<String, String> reqMap = RequestUtils.getReqMap(request);
//		String str = reqMap.get("Plain");
		// 获取支付结果明文
		String plain = request.getParameter("Plain");
		// 签名
		String signature = request.getParameter("Signature");
		String code = "ok";
		Map<String, String> map = new HashMap<String, String>();
		if(plain == null || plain.equals("")) {
			code = "301"; // 支付失败
		} else {
			// 签名验证
			boolean validate = SignatureService.verify(plain, signature);
			if(validate) {
				// 验证签名成功
				// Plain=TranAbbr=IPER|AcqSsn=000000008448|MercDtTm=20160919155759|TermSsn=20160919155759896|
				// RespCode=00000000|TermCode=111|MercCode=1100529310001000003|TranAmt=100.00|SettDate=20141021|, EMPTEMP=TEMP, orderTime=20160919155759, showOrderamt=100.00 元
				plain = plain.replace("|", ",");
				String[] array = plain.split(",");
				for(int i = 0; i < array.length; i++) {
					String arrStr = array[i];
					if(arrStr != null && !arrStr.equals("")) {
						String[] keys = arrStr.split("=");
						// 获取RespCode
						if(keys[0] != null && keys[0].equals("RespCode")) {
							if(keys[1] != null && keys[1].equals("00000000")) {
								// 支付成功
								// 支付成功推送消息
								TransmissionTemplate template = new TransmissionTemplate();
								APNPayload payload = new APNPayload();
								AppPush push = new AppPush();
								Model user = (Model) request.getSession().getAttribute("user");
								String alias = user.getString("AA001"); // 用户ID
//							String alias = "602c8a5b-5748-47cd-b4d3-6f9fa0425cdd";
								map.put("AAE011", alias);
								// 透传消息设置，1为强制启动应用，客户端接收到消息后就会立即启动应用；2为等待应用启动
								JSONObject pushData = new JSONObject();
								pushData.put("t", "1");//业务办理类型
								pushData.put("m", "缴费通知");//通知头
								pushData.put("d", "缴费成功");//通知内容
								if(AppPush.getUserStatus(alias)) {
									template.setTransmissionContent(pushData.toString());
								}else{
									payload.addCustomMsg("t", pushData.get("t"));
									payload.addCustomMsg("m", pushData.get("m"));
									payload.addCustomMsg("d", pushData.get("d"));
									template.setAPNInfo(payload);
								}
								try {
									push.pushtoSingle(template, alias, payload);
								} catch (Exception e) {
									e.printStackTrace();
								}
								notice.add(pushData, alias);
								code = "ok";
							} else {
								code = "301"; // 支付失败
							}
							map.put("RespCode", keys[1]); // 返回码
						} else if(keys[0] != null && keys[0].equals("TermSsn")) {
							map.put("TermSsn", keys[1].substring(0, keys[1].length()-7));// 订单号
						} else if(keys[0] != null && keys[0].equals("TranAmt")) {
							map.put("TranAmt", keys[1]); // 交易金额
						} else if(keys[0] != null && keys[0].equals("MercDtTm")) {
							map.put("MercDtTm", keys[1]); // 商户日期时间
						} else if(keys[0] != null && keys[0].equals("AcqSsn")) {
							map.put("AcqSsn", keys[1]); // 支付平台流水
						} else if(keys[0] != null && keys[0].equals("账号")) {
							map.put("payNo", "999999"); // 支付账号
						}
					}
				}
			} else {
				// 验证签名失败
				code = "301";
			}
		}
		String str = "";
		response.setContentType("text/html;charset=" + "UTF-8");
		response.setCharacterEncoding("UTF-8");
		if(code.equals("ok")) {
			map.put("bankType", "YC"); // 银行类别,YC:邮储，NH:农行，JH：建行
			map.put("AAC002", request.getSession().getAttribute("orderWriteCA006").toString()); // 身份证号
			if(code != null && !code.equals("") && code.equals("ok")) {
				// 支付成功，回填业务系统订单数据
				map.put("AAE010", "999999");
				JSONObject object = orderBackWriteService.orderBackWrite(map);
				if(object.getBooleanValue("SUCCESS")) {
					// 返回支付成功页面
					str = "	<img alt='' src='img/success.png' style='/* align-self: center; */.aligncenter "
		    			+ "{clear: both;display: block;margin:auto;  }.aligncenter {clear: both;display: "
		    			+ "block;margin:auto;  }clear: both;display: block;margin:auto;margin-top: 200px;'>"
		    			+ "<span class='title' style='text-align: center;clear: both;display: block;"
		    			+ "margin-top: 30px;font-size: 20px;width:100px, height:100px'>支付成功</span>";
//					response.sendRedirect("bank/ResultSuccess.jsp");
				} else {
					// 返回支付失败页面
					str = "<img alt='' src='img/error.png' style='/* align-self: center; */.aligncenter "
						+ "{clear: both;display: block;margin:auto;  }.aligncenter {clear: both;display: block;"
						+ "margin:auto;  }clear: both;display: block;margin:auto;margin-top: 200px;>"
						+ "<span class='title' style='text-align: center;clear: both;display: block;margin-top: 30px;"
						+ "font-size: 40px;'>支付失败</span><span style='text-align: center;clear: both;display: block;"
						+ "margin-top: 30px;font-size: 20px;width:100px, height:100px';margin-left: 100px;margin-right: 100px;'>如果银行已经扣款成功，"
						+ "请您次日在“我的”-“订单查询”查询订单支付信息！</span>";
//					response.sendRedirect("bank/ResultFail.jsp");
				}
			}
		} else {
			// 返回支付失败页面
			str = "<img alt='' src='img/error.png' style='/* align-self: center; */.aligncenter "
				+ "{clear: both;display: block;margin:auto;  }.aligncenter {clear: both;display: block;"
				+ "margin:auto;  }clear: both;display: block;margin:auto;margin-top: 200px;>"
				+ "<span class='title' style='text-align: center;clear: both;display: block;margin-top: 30px;"
				+ "font-size: 40px;'>支付失败</span><span style='text-align: center;clear: both;display: block;"
				+ "margin-top: 30px;font-size: 20px;width:100px, height:100px';margin-left: 100px;margin-right: 100px;'>如果银行已经扣款成功，"
				+ "请您次日在“我的”-“订单查询”查询订单支付信息！</span>";
//			response.sendRedirect("bank/ResultFail.jsp");
		}
		response.getWriter().write(str);
		//response.sendRedirect("bank/bankResult.html?code="+code);
	}
	/**
	 * 手机支付交易
	 */
//	public void psbcPay() {
//		String transName = "WPER"; // 交易名称
//		// 交易数据明文数据封装开始
//		String TranAbbr = "WPER"; // 交易缩写   必填
//		String MercDtTm = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); // 商户日期时间 必填
//		String TermSsn = getParam("orderNumber"); //订单号 必填
//		String OSttDate = ""; // 原交易商户日期
//		String OAcqSsn = ""; // 原交易订单号
//		String MercCode = "1100529310001000003"; // 商户号 必填  测试数据：1100529310001000003
//		String TermCode = ""; // 终端号
//		String TranAmt = getParam("orderAmount"); // 交易金额 必填
//		String MercUrl = "http://"+context.getRequest().getRemoteHost()+"/bank/psbcPayResult.json?appId=6103_web&sig=xxx"; // 商户通知地址
//		String Remark1 = ""; // 备注1
//		String Remark2 = ""; // 备注2
//		String LimitTime = ""; // 有效时间
//		// 交易数据明文数据封装结束
//		// 交易数据明文
//		String Plain = "TranAbbr="+TranAbbr+"|MercDtTm="+MercDtTm+"|TermSsn="+TermSsn+"|OSttDate="
//				+OSttDate+"|OAcqSsn="+OAcqSsn+"|MercCode="+MercCode+"|TermCode="+TermCode
//				+"|TranAmt="+TranAmt+"|MercUrl="+URLEncoder.encode(MercUrl)+"|Remark1="+Remark1+"|Remark2="
//				+Remark2+"|LimitTime="+LimitTime;
//		
//		// 交易数据明文签名
//		String Signature = SignatureService.sign(Plain);
//
//		String response= "";//要返回的response信息
//        HttpClient httpClient = new HttpClient();
//        PostMethod postMethod = new PostMethod("http://103.22.255.201:8443/psbcpay/main");
//        //填入各个表单域的值
//        NameValuePair[] data = {
//          new NameValuePair("transName", transName),
//          new NameValuePair("Plain", Plain),
//          new NameValuePair("Signature", Signature),
//        };
//        // 将表单的值放入postMethod中
//        postMethod.setRequestBody(data);
//        // 执行postMethod
//        int statusCode = 0;
//        try {
//            statusCode = httpClient.executeMethod(postMethod);
//        } catch (HttpException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        // HttpClient对于要求接受后继服务的请求，象POST和PUT等不能自动处理转发
//        // 301或者302
//        if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {  
//            // 从头中取出转向的地址
//            Header locationHeader = postMethod.getResponseHeader("location");
//            String location = null;
//            if (locationHeader != null) {
//                location = locationHeader.getValue();
//            }
//        } else {
//            try {
//                response= postMethod.getResponseBodyAsString();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            postMethod.releaseConnection();
//        }
//        // 将支付页面信息返回
//        datas.put("info", response);
//	}
	
	public static void main(String[] args) {
		String transName = "WPER"; // 交易名称
		// 交易数据明文数据封装开始
		String TranAbbr = "WPER"; // 交易缩写   必填
		String MercDtTm = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); // 商户日期时间 必填
		String TermSsn = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()); //订单号 必填
		String OSttDate = ""; // 原交易商户日期
		String OAcqSsn = ""; // 原交易订单号
		String MercCode = "1100529310001000003"; // 商户号 必填  测试数据：1100529310001000003
		String TermCode = ""; // 终端号
		String TranAmt = "100"; // 交易金额 必填
		String MercUrl = "http://127.0.0.1:8080/bank/psbcPayResult.json?appId=6103_web&sig=xxx"; // 商户通知地址
		String Remark1 = ""; // 备注1
		String Remark2 = ""; // 备注2
		String LimitTime = ""; // 有效时间
		// 交易数据明文数据封装结束
		// 交易数据明文
		@SuppressWarnings("deprecation")
		String Plain = "TranAbbr="+TranAbbr+"|MercDtTm="+MercDtTm+"|TermSsn="+TermSsn+"|OSttDate="
				+OSttDate+"|OAcqSsn="+OAcqSsn+"|MercCode="+MercCode+"|TermCode="+TermCode
				+"|TranAmt="+TranAmt+"|MercUrl="+URLEncoder.encode(MercUrl)+"|Remark1="+Remark1+"|Remark2="
				+Remark2+"|LimitTime="+LimitTime;
		
		// 交易数据明文签名
		String Signature = SignatureService.sign(Plain);

		String response= "";//要返回的response信息
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod("http://103.22.255.201:8443/psbcpay/main");
        //填入各个表单域的值
        NameValuePair[] data = {
          new NameValuePair("transName", transName),
          new NameValuePair("Plain", Plain),
          new NameValuePair("Signature", Signature),
        };
        // 将表单的值放入postMethod中
        postMethod.setRequestBody(data);
        // 执行postMethod
        int statusCode = 0;
        try {
            statusCode = httpClient.executeMethod(postMethod);
            if(statusCode == HttpStatus.SC_OK) {
            	// 消息推送
//            	msgNotice();
            }
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // HttpClient对于要求接受后继服务的请求，象POST和PUT等不能自动处理转发
        // 301或者302
        if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {  
            // 从头中取出转向的地址
            Header locationHeader = postMethod.getResponseHeader("location");
            @SuppressWarnings("unused")
			String location = null;
            if (locationHeader != null) {
                location = locationHeader.getValue();
            }
        } else {
            try {
                response= postMethod.getResponseBodyAsString();
            } catch (IOException e) {
                e.printStackTrace();
            }
            postMethod.releaseConnection();
        }
        System.out.println(response);
	}
}
